from flask import Flask
from applications.config import BaseConfig
from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor

# 配置 jobstores 和 executors
# jobstores = {
#     'default': SQLAlchemyJobStore(url='sqlite:///../jobs.sqlite')  # 使用 SQLite 数据库存储任务
# }
jobstores = BaseConfig.SCHEDULER_JOBSTORES
executors = {
    'default': ThreadPoolExecutor(10)
}

def init_scheduler(app: Flask):
    """
    初始化调度器并将其绑定到 Flask 应用中。
    """
    try:
        scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors)
        scheduler.start()
        app.config['SCHEDULER'] = scheduler
        app.logger.info("Scheduler initialized and started.")
    except Exception as e:
        app.logger.error(f"Scheduler initialization failed: {str(e)}")